<template>
	<view class="content">
	  <view>
		<zero-loading  type="love" v-if="loading"></zero-loading>
	    <!-- <button @click="getCode">=={{code}}</button>
		<u--textarea placeholder="请输入内容" v-model="openid" ></u--textarea> -->
	  </view>
	
	</view>
</template>

<script>
/* 
1.本页面必须挂在的微信公众号的菜单上才能使用;
2.本页地址只能在外网访问内网访问不了，因为会公众号会动态返回code参数
3.本务的功能主要获取用户的微信的code和openid;
 */
export default {
	data() {
	  return {
	    //homeUrl: "http://ksh.ctruck.com.cn/login/uni/",
		//homeUrl: "http://ksh1.ctruck.com.cn/pages/login/pre_gzh_login",
		homeUrl:"",//没什么用
	    //APPID: "wxdd313b0e8754378a",
	    //APPSECRET: "cef5ee71d5c83a56e398116043e03d64",
	    userInfo: {},
		code:"",
		openid:"",
		loading:true,
	  };
	},
	 onLoad(){
	        this.getCode()
	    },
	methods:{
	    getCode() {
			    //console.log(this.code)
				var local = encodeURIComponent(this.homeUrl); // 当前H5页面的url
				var appid = 'wx7897cb67b0a0b45e';//集瑞信息平台appid=wx7897cb67b0a0b45e
				this.code = this.getUrlCode().code; // 截取code
					// 如果没有code，则去请求
				if (this.code == null || this.code === '' || this.code == undefined) {
					var wxUrl =
						'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
						appid +
						'&redirect_uri=' +
						local +
						'&response_type=code' +
						'&scope=snsapi_base' +
						'&state=STATE#wechat_redirect';
					window.location.href = wxUrl;
				} else {
					//console.log(this.code);
					// 存在code 获取openid
					this.http.get("/api/customer/get_openid?code="+this.code).then(x => {
						//this.openid="真实姓名："+x.data.userName;
						//return;
						if (x.status==true){//系统自动登录，并转入到Home页
							this.$store.commit("setUserInfo", x.data);//这步不能少，表示客户端登录成功
							uni.switchTab({
								url: "/pages/home/home"
							})
							//this.openid=x.data;
						}else{//其他情况都需要登录
						    if (x.data.wxopenid!=""){
								//this.openid="啥也没获取到"+x.data.wxopenid;
								uni.navigateTo({
									url: "/pages/login/login?openid="+x.data.wxopenid,
								})
							}			
							//this.openid=x.code;
						}
					});
				}
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.href; //获取打开的公众号的路径
				let winUrl = url;
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(url.indexOf('?') + 1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						var items = strs[i].split('=');
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
					}
				}
				return theRequest;
			}
	}
}
</script>

<style>
</style>
